//
//  QQShareCenter.m
//  Weibbo
//
//  Created by 李 林刚 on 13-8-14.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "QQShareCenter.h"

#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import <TencentOpenAPI/TencentOAuth.h>

#import "ASIFormDataRequest.h"
#import "JSONKit.h"

#define    QZone_OAuth           @"QZone"
#define    AccessToken           @"access_token"
#define    ExpirationDate        @"expirationDate"
#define    QZone_OpenID          @"openid"

@interface QQShareCenter ()<TencentSessionDelegate,ASIHTTPRequestDelegate>
{
    
    TencentOAuth    *tencentOAuth;
    NSMutableArray * permissions;

    NSString  *accessToken;
    NSString  *expirationDate;
    NSString  *openId;
}
@end

@implementation QQShareCenter
@synthesize delegate;

-(void)dealloc
{
    UIRelease(tencentOAuth);
    UIRelease(permissions);
    UIRelease(accessToken);
    UIRelease(expirationDate);
    UIRelease(openId);
    [super dealloc];
}

-(id)initWithDelegate:(id<QQShareCenterDelegate>)qqdelegate
{
    self = [super init];
    if (self) {
        delegate = qqdelegate;
        permissions = [[NSArray arrayWithObjects:
                        kOPEN_PERMISSION_GET_USER_INFO,
                        kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                        kOPEN_PERMISSION_ADD_ALBUM,
                        kOPEN_PERMISSION_ADD_IDOL,
                        kOPEN_PERMISSION_ADD_ONE_BLOG,
                        kOPEN_PERMISSION_ADD_PIC_T,
                        kOPEN_PERMISSION_ADD_SHARE,
                        kOPEN_PERMISSION_ADD_TOPIC,
                        kOPEN_PERMISSION_CHECK_PAGE_FANS,
                        kOPEN_PERMISSION_DEL_IDOL,
                        kOPEN_PERMISSION_DEL_T,
                        kOPEN_PERMISSION_GET_FANSLIST,
                        kOPEN_PERMISSION_GET_IDOLLIST,
                        kOPEN_PERMISSION_GET_INFO,
                        kOPEN_PERMISSION_GET_OTHER_INFO,
                        kOPEN_PERMISSION_GET_REPOST_LIST,
                        kOPEN_PERMISSION_LIST_ALBUM,
                        kOPEN_PERMISSION_UPLOAD_PIC,
                        kOPEN_PERMISSION_GET_VIP_INFO,
                        kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                        kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                        kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                        nil]retain];
        tencentOAuth = [[TencentOAuth alloc] initWithAppId:APPID_QQ andDelegate:self];
    }
    return self;
}

- (BOOL)IsQQSessionValid
{
    NSDictionary  *QzonOAuthDic = [[NSUserDefaults standardUserDefaults]objectForKey:QZone_OAuth];
    if (QzonOAuthDic)
    {
        accessToken = [[QzonOAuthDic objectForKey:AccessToken]retain];
        expirationDate = [[QzonOAuthDic objectForKey:ExpirationDate]retain];
        openId = [[QzonOAuthDic objectForKey:QZone_OpenID]retain];
        if (openId!=nil&&[openId length]>0&&accessToken!=nil&&[accessToken length]>0&&NSOrderedDescending == [expirationDate compare:[NSDate date]])return YES;
        else return NO;
    }
    else return NO;
}

- (void)QQStartAuthorize
{
  [tencentOAuth authorize:permissions localAppId:APPID_QQ inSafari:NO];
}

- (void)QQLoginOut
{
    [tencentOAuth logout:self];
}

//分享
/*
 1. 用户评论：用户在第三方网站发布的评论等UGC信息，对应的参数为“comment”，选填项。
 2. 分享的内容标题，含源网页URL，点击跳转至第三方网站网页，对应的参数为“title”和“url”，必填项。
 3. 详细描述：网页摘要，对应的参数为“summary”，选填项。
 如果分享到微博平台，则摘要内容不会在微博中显示，若希望在微博中展示分享的内容，建议将重要信息在评论中进行描述。
 4. 外部图片：引用外部图片（大小不超过100 x 100 px），对应的参数为“images”，选填项。
 5. 来源网站名称及域名：标明分享的来源，对应的参数为“site”和“fromurl”，必填项
 
 access_token=*************
 oauth_consumer_key=200003
 openid==**********
 title=QQ空间
 site	 必须	 string	 分享的来源网站名称，请填写网站申请接入时注册的网站名称，对应上文接口说明的5。
 fromurl	 必须	 string	 分享的来源网站对应的网站地址url，对应上文接口说明中5的超链接。
 请以http://开头。
 url=http://www.qzone.com/
 images=http://imgcache.qq.com/QzonePortal_v2/city_v2/img/news_img/2011/0526/portal_new_1306376959_375.jpg
 */

- (void)shareToQZone:(NSArray *)contentArr
{
    ASIFormDataRequest  *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"https://graph.qq.com/share/add_share"]];
    request.delegate = self;
    [request setPostValue:accessToken forKey:AccessToken];
    [request setPostValue:APPID_QQ forKey:@"oauth_consumer_key"];
    [request setPostValue:openId forKey:QZone_OpenID];
    
    [request setPostValue:[contentArr objectAtIndex:0] forKey:@"title"];
    
    //分享所在网页资源的链接，点击后跳转至第三方网页，对应上文接口说明中2的超链接。请以http://开头。
    [request setPostValue:[NSURL URLWithString:@"http://www.baidu.com"] forKey:@"url"];
    //所分享的网页资源的代表性图片链接"，对应上文接口说明的4。请以http://开头，长度限制255字符。多张图片以竖线（|）分隔，目前只有第一张图片有效，图片规格100*100为佳。
    [request setPostValue:[contentArr objectAtIndex:2] forKey:@"images"];
    //分享的来源网站名称，请填写网站申请接入时注册的网站名称，对应上文接口说明的5。
    [request setPostValue:@"weibbbo" forKey:@"site"];
    //分享的来源网站对应的网站地址url，对应上文接口说明中5的超链接。请以http://开头。
    [request setPostValue:@"http://www.baidu.com" forKey:@"fromurl"];
    [request startAsynchronous];
}

#pragma mark - ASIHttpRequestDelegate

-(void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"request.error  %@",request.error);
    NSLog(@"request.responseString  %@",request.responseString);
    NSDictionary *dic = [request.responseString objectFromJSONString];
    if ([[dic objectForKey:@"ret"]integerValue]==0) {
        if ([delegate respondsToSelector:@selector(QQDidShareScucess:)]) {
            [delegate QQDidShareScucess:YES];
        }
    }
    else
    {
        if ([delegate respondsToSelector:@selector(QQDidShareScucess:)]) {
            [delegate QQDidShareScucess:NO];
        }
    }

}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"request.error  %@",request.error);
    NSLog(@"request.responseString  %@",request.responseString);
    if ([delegate respondsToSelector:@selector(QQDidShareScucess:)]) {
        [delegate QQDidShareScucess:NO];
    }
}

#pragma mark - TencentOAuth Login callback
/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin
{
    if (tencentOAuth.accessToken&& 0 != [tencentOAuth.accessToken length])
    {//记录登陆后的数据信息
        NSMutableDictionary *oauthDic = [[NSMutableDictionary alloc]init];
        [oauthDic setObject:tencentOAuth.accessToken forKey:AccessToken];
        [oauthDic setObject:tencentOAuth.expirationDate forKey:ExpirationDate];
        [oauthDic setObject:tencentOAuth.openId forKey:QZone_OpenID];
        [[NSUserDefaults standardUserDefaults]setObject:oauthDic forKey:QZone_OAuth];
        [oauthDic release];
        if ([delegate respondsToSelector:@selector(QQDidLogin)]) {
            [delegate QQDidLogin];
        }
    }
}
/**
 * 登录失败后的回调
 * param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if ([delegate respondsToSelector:@selector(QQDidNotLogin:)]) {
        [delegate QQDidNotLogin:cancelled];
    }
}
/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
    if ([delegate respondsToSelector:@selector(QQDidNotNetWork)]) {
        [delegate QQDidNotNetWork];
    }
}

/**
 *退出登录
 */
-(void)tencentDidLogout
{
   [[NSUserDefaults standardUserDefaults]removeObjectForKey:QZone_OAuth];
    if ([delegate respondsToSelector:@selector(QQDidLogout)]) {
        [delegate QQDidLogout];
    }
}

@end
